from audioop import reverse
from datetime import datetime

from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from requests import request

from demo.models import Classes, Userdetail, Article, Label
from user.form import UserForm


# Create your views here.
def test(request, info):
    print(info)
    print('test')
    return HttpResponse('hello world')


def re_test(request, **kwargs):
    info = kwargs.get('info')
    return HttpResponse(f're_test{info}')

#
# data = {'python': [{"title": "【Python】探索 PyTorch 在机器学习中的应用",
#                     "desc": "在机器学习的浪潮中，PyTorch 以其灵活性和易用性成为了研究者和开发者的热门选择。本文将探讨 PyTorch 在机器学习领域的应用，并展示如何使用 PyTorch 构建一个基本的机器学习模型。",
#                     "detail": "https://blog.csdn.net/jacksoon/article/details/142416740?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-3-142416740-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-3-142416740-null-null.nonecase",
#                     "img": "https://i-blog.csdnimg.cn/direct/8e8fd74e4da242c8bd9b5456eeecd9f4.jpeg?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
#                     'create_time': datetime(2024, 10, 19, 16, 7),
#                     },
#                    {"title": "Python爬虫入门实例：Python7个爬虫小案例（附源码）",
#                     "desc": "通过本文的讲解，相信读者已经对Python爬虫有了较为全面的认识。爬虫技能在数据分析、自然语言处理等领域具有广泛的应用，希望读者能够动手实践，不断提高自己的技能水平。同时，请注意合法合规地进行爬虫，遵守相关法律法规。祝您学习愉",
#                     "detail": "https://blog.csdn.net/Candyz7/article/details/139808637?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-16-139808637-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-16-139808637-null-null.nonecase",
#                     "img": "https://img-blog.csdnimg.cn/direct/f9f7ff2bac44491d92050a64a601e267.jpeg?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
#                     'create_time': datetime(2024, 4, 2, 16, 7),
#                     },
#                    {"title": "Python传递参数的5种方式",
#                     "desc": "在定义函数时，我们有时候并不知道调用的时候会传递多少个参数。这时候，包裹（packing）位置参数或者包裹关键字参数来进行参数传递会非常有用。给函数的输入参数设定一个默认值,如果该参数最终没有输入,则使用默认参数出入函数.在fun4的参数表",
#                     "detail": "https://blog.csdn.net/2301_80632101/article/details/138305595?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-15-138305595-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-15-138305595-null-null.nonecase",
#                     "img": "https://img-blog.csdnimg.cn/img_convert/fad536e972e14ce4b37803185dc3b00c.png?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
#                     'create_time': datetime(2024, 4, 2, 16, 7),
#                     }
#                    ],
#         'java': [{
#             "title": "Java之反射",
#             "desc": "反射的定义，主要用途，反射相关的类和方法，以及反射的优缺点。",
#             "detail": "https://blog.csdn.net/wmh_1234567/article/details/141277191",
#             "img": "https://i-blog.csdnimg.cn/direct/3f26a21f04cf4382b6cdc05b8347a3b4.png?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
#             'create_time': datetime(2024, 4, 2, 16, 7),
#         },
#             {
#                 "title": "Java中的红黑树（如果想知道Java中有关红黑树的知识点，那么只看这一篇就足够了！",
#                 "desc": "Java中的红黑树（如果想知道Java中有关红黑树的知识点，那么只看这一篇就足够了！）",
#                 "detail": "https://blog.csdn.net/2302_80198073/article/details/142334946?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-8-142334946-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-8-142334946-null-null.nonecase",
#                 "img": "https://i-blog.csdnimg.cn/direct/746e082683c6443e93439cb4dbf21a40.jpeg?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
#                 'create_time': datetime(2024, 4, 2, 16, 7),
#             }
#         ],
#         'ai': [{
#             'create_time': datetime(2024, 4, 2, 16, 7),
#         }]
#         }

# user = {
#     'name': 'lili',
#     'sex': '女',
#     'age': 18
# }


# user=None

def nav(request, **kwargs):
    print(request.user.username)
    classes = kwargs.get('classes')
    if not Classes.objects.filter(name=classes).exists():
        return redirect('not_find')
    try:
        res=Classes.objects.get(name=classes)
    except Classes.DoesNotExist:
        return redirect('not_find')
    return render(
        request,
        'demo/nav.html',
        context={
            'articles': res.article_set.all(),
            'html': '<h1>hello django</h1>',
            # 把字典的分类数据返回出去
            'classes': Classes.objects.all(),
            # 把获取到的地址值对应的类目传给模版
            'now_cls': classes,
            'username':request.session.get('username')
        }
    )


def index(request, **kwargs):
    return render(request,'demo/index.html',{
        'classes':Classes.objects.all(),
        'username':request.session.get('username')
    })



def not_found(request, **kwargs):
    return HttpResponse('输入的信息有误，没有相关信息！！！')

#添加数据
def add_classes(request, **kwargs):
    #方式一
    classes1=Classes(name='python')
    classes1.save()
    #方式二（不常用）
    classes2=Classes()
    classes2.name='java'
    classes2.save()
    #方式三(常用,不需要而外调用保存)
    Classes.objects.create(name='mysql')
    #方式四（不常用）
    res=Classes.objects.get_or_create(name='python')  #有则获取数据，无则创建数据
    print(res)
    return HttpResponse('数据添加成功')

#获取数据
def get_classes(request, **kwargs):
    #查询所有数据
    res=Classes.objects.all()
    for i in res:
        print(i.name)
    java=Classes.objects.get(name='java')  #get只能获取单条数据
    print(java)
    python=Classes.objects.filter(name='python') #filter用来查询多条数据
    print(python)
    python=Classes.objects.get(id=2)
    print(python)
    return HttpResponse('查询数据成功')

#更新数据
def update_classes(request, **kwargs):
    #先查询需要修改的数据，再通过属性值进行修改
    # res=Classes.objects.get(name='mysql')
    # res.name='php'
    # res.save()
    Classes.objects.filter(name='mysql').update(name='php')  #创建对象方式修改则用update属性
    return HttpResponse('修改数据成功')

#删除数据
def del_classes(request, **kwargs):
    Classes.objects.get(name='java1').delete()
    return HttpResponse('删除数据成功')

#常用查询条件
def find_conditions(request,**kwargs):
    print('忽略大小写匹配',Classes.objects.filter(name__iexact="MYSQL"))
    print('包含',Classes.objects.filter(name__contains='a'))
    print('以什么开始',Classes.objects.filter(name__startswith='j'))
    print('以什么结尾',Classes.objects.filter(name__endswith='p'))
    print('成员',Classes.objects.filter(name__in=['java','php']))
    print('大于',Classes.objects.filter(id__gt=3))
    print('大于等于',Classes.objects.filter(id__gte=3))
    print('区间',Classes.objects.filter(id__range=(2,5)))
    print('是否为空',Classes.objects.filter(name__isnull=False))
    return HttpResponse('查询成功')


def test1(request):
    user=User(username='test')
    user.set_password('qwe123')
    user.save()
    user=User.objects.get(username='test')
    Userdetail.objects.create(age=18,sex=1,user=user)
    user=User.objects.get(username='test')
    print(user.userdetail.sex)
    userdetail=Userdetail.objects.get(id=1)
    print(userdetail.user.username)
    return HttpResponse('成功')

def get_article(request):
    classes=Classes.objects.get(name='python')
    print(classes.a.all())
    return HttpResponse('获取文章内容成功')

def onetomany(request,**kwargs):
    # classes1=Classes.objects.get_or_create(name='python')
    # classes2=Classes.objects.get_or_create(name='java')
    # article1=Article(
    #     title='【Python】探索 PyTorch 在机器学习中的应用',
    #     desc='在机器学习的浪潮中，PyTorch 以其灵活性和易用性成为了研究者和开发者的热门选择。本文将探讨 PyTorch 在机器学习领域的应用，并展示如何使用 PyTorch 构建一个基本的机器学习模型。',
    #     content="https://blog.csdn.net/jacksoon/article/details/142416740?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-3-142416740-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-3-142416740-null-null.nonecase",
    #     cover="https://i-blog.csdnimg.cn/direct/8e8fd74e4da242c8bd9b5456eeecd9f4.jpeg?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
    #     user_id=1,
    #     classes_id=4
    # )
    # article2 = Article(
    #     title='Java之反射',
    #     desc="反射的定义，主要用途，反射相关的类和方法，以及反射的优缺点",
    #     content="https://blog.csdn.net/2302_80198073/article/details/142334946?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-8-142334946-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-8-142334946-null-null.nonecase",
    #     cover="https://i-blog.csdnimg.cn/direct/746e082683c6443e93439cb4dbf21a40.jpeg?x-oss-process=image/resize,m_fixed,h_300,image/format,png",
    #     user_id=1,
    #     classes_id=6
    # )
    # article1.save()
    # article2.save()
    classes1=Classes.objects.get(name='python')
    res=classes1.article_set.all()
    print(res)
    return HttpResponse('成功')

def manytomany(request,**kwargs):
    # article1=Article.objects.get(id=1)
    # article2=Article.objects.get(id=3)
    # print(article1)
    # print(article2)
    # article1.label.create(name='python')
    # article2.label.create(name='java')
    # article1.save()
    # article2.save()
    # #删除表数据
    # article1.label.remove(Label.objects.get(id=1))
    # #移除文章的所有标签
    # article1.label.clear()
    res1=Classes.objects.get(name='python').article_set.all()
    res2=Article.objects.filter(classes__name='python')
    res3=User.objects.get(name='test').article_set.all()
    res4=Article.objects.filter(classes__name='test')
    res5=User.objects.get(username='test').userdetail.age
    res6=Userdetail.objects.filter(user__username='test').age
    print(res6)
    return HttpResponse('成功')